<!--
 * @Author: aster lipian1004@163.com
 * @Date: 2025-02-20 16:55:21
 * @FilePath: \aster-flowable-uniapp\src\components\form\render\area.vue
 * @Description: 省市区
 * Copyright (c) 2025 by Aster, All Rights Reserved.
-->
<template>
  <van-field
    v-if="!_hidden"
    v-model="_value"
    :name="formItemProp"
    :placeholder="_placeholder"
    :readonly="true"
    :required="_required"
    :rules="_rules"
    :input-align="FieldInputAlignEnum.RIGHT"
    :error-message-align="FieldInputAlignEnum.RIGHT"
    :label-width="showLabel ? '' : '5rpx'"
    is-link
    @click="handleOpen"
  >
    <template #label>
      <text v-if="showLabel">{{ formItem.title }}</text>
    </template>
  </van-field>
  <van-popup v-model:show="showPicker" round position="bottom">
    <van-cascader
      v-if="!_readonly"
      v-model="_value"
      title="请选择所在地区"
      :options="treeData"
      :field-names="customFieldName"
      @close="showPicker = false"
      @finish="handleConfirm"
    />
  </van-popup>
</template>
<script setup lang="ts">
  import { evaluateFormula } from '@/utils/workflow';
  import { computed, onMounted, PropType, ref } from 'vue';
  import { isNotEmpty } from '@/utils/is';
  import { areaList } from '@vant/area-data';
  import { FormPermissionEnum } from '@/enums/workFlowEnum';
  import { FieldInputAlignEnum } from '@/enums/formEnum';

  const emit = defineEmits(['update:value']);
  const props = defineProps({
    value: {
      type: String,
      default: '',
    },
    mode: {
      type: String as PropType<'design' | 'form' | 'search' | 'table' | 'print'>,
      default: 'design',
    },
    formData: {
      type: Object as PropType<WorkForm.FormDataModel>,
      default: {},
    },
    formItem: {
      type: Object as PropType<WorkComponent.ComponentConfig>,
      default: {},
    },
    tableId: {
      type: String,
      default: '',
    },
    tableIndex: {
      type: Number,
      default: 0,
    },
    showLabel: {
      type: Boolean,
      default: true,
    },
  });

  // 节点树
  const treeData = ref<WorkComponent.TreeNode[]>([]);
  // 显示弹出层
  const showPicker = ref(false);
  // 自定义Columns的结构
  const customFieldName = {
    text: 'label',
    value: 'value',
    children: 'children',
  };

  // 打开弹出层
  const handleOpen = () => {
    if (!_readonly.value) {
      showPicker.value = true;
    }
  };

  // 确认选择
  const handleConfirm = ({ selectedOptions }) => {
    _value.value = selectedOptions.map((option) => option.label).join('-');
    showPicker.value = false;
  };

  /**
   * @description: 加载节点数据
   * @return {*}
   */
  const loadTreeData = async () => {
    const provinceList = { ...areaList.province_list };
    const cityList = { ...areaList.city_list };
    const countyList = { ...areaList.county_list };

    treeData.value.length = 0;

    // 遍历省列表
    Object.keys(provinceList).forEach((provinceKey) => {
      const province: WorkComponent.TreeNode = {
        label: provinceList[provinceKey],
        value: provinceList[provinceKey],
        children: [],
      };

      // 如果级别大于2
      if (props.formItem.props.level >= 2) {
        // 遍历市数据
        Object.keys(cityList).forEach((cityKey) => {
          const cityDistance = Number(cityKey) - Number(provinceKey);
          if (cityDistance > 0 && cityDistance < 10000) {
            const city: WorkComponent.TreeNode = {
              label: cityList[cityKey],
              value: cityList[cityKey],
              children: [],
            };
            if (props.formItem.props.level > 2) {
              Object.keys(countyList).forEach((countyKey) => {
                const countyDistance = Number(countyKey) - Number(cityKey);
                if (countyDistance > 0 && countyDistance < 100) {
                  const county: WorkComponent.TreeNode = {
                    label: countyList[countyKey],
                    value: countyList[countyKey],
                  };
                  delete countyList[countyKey];
                  city.children?.push(county);
                }
              });
            } else {
              city.children = undefined;
            }
            delete cityList[cityKey];
            province.children?.push(city);
          }
        });
      } else {
        province.children = undefined;
      }
      delete provinceList[provinceKey];
      treeData.value.push(province);
    });
  };

  /**
   * @description: 提示词
   */
  const _placeholder = computed(() => {
    if (_readonly.value) {
      return '';
    }
    return isNotEmpty(_value.value) ? '' : props.formItem.props.placeholder;
  });

  // 键
  const formItemProp = computed(() => {
    if (isNotEmpty(props.tableId)) {
      return props.tableId + '.' + props.tableIndex + '.' + props.formItem.id;
    } else {
      return props.formItem.id;
    }
  });

  /**
   * @description: 组件值
   */
  const _value = computed({
    get() {
      return props.value;
    },
    set(val) {
      emit('update:value', val);
    },
  });

  /**
   * @description: 是否必填, true-必填
   */
  const _required = computed(() => {
    return props.formItem.props.required;
  });

  /**
   * @description: 校验规则
   */
  const _rules = computed(() => {
    const isRequired = _required.value;
    if (props.mode != 'form') {
      return [];
    }
    return isRequired ? [{ required: true, message: `请输入${props.formItem.title}` }] : [];
  });

  /**
   * @description: 是否隐藏, true-隐藏
   */
  const _hidden = computed(() => {
    let r = false;
    // 解析隐藏条件公式
    if (props.formItem.props.hidden) {
      let expression = props.formItem.props.hidden;
      // 如果是子表中的控件，则需要用到下标
      if (isNotEmpty(props.tableId)) {
        expression = expression.replaceAll('?', props.tableIndex);
      }
      r = evaluateFormula(expression, props.formData);
    }
    // 判断流程节点下该控件是否隐藏
    if (props.formItem.operation && props.formItem.operation.length > 0) {
      r = r || props.formItem.operation[0] == FormPermissionEnum.HIDDEN;
    }
    return r;
  });

  /**
   * @description: 是否只读, true-只读
   */
  const _readonly = computed(() => {
    let r = props.formItem.props.readonly;
    if (props.formItem.operation && props.formItem.operation.length > 0) {
      r = r || props.formItem.operation[0] == FormPermissionEnum.READONLY;
    }
    return r;
  });

  onMounted(() => {
    loadTreeData();
  });

  defineExpose({
    _hidden,
  });
</script>
<style scoped lang="scss"></style>
